package indi.storyoftime.rasite.util;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片相关工具类
 */
public class ImageUtil {

    public static void main(String[] args) throws IOException {
        String path = "/Users/zhangzheng/IdeaProjects/story-image-host/debug/image/IMG_20210920_184133.jpg";
        try(FileInputStream file = new FileInputStream(path)) {
            Map<String, String> map = ImageUtil.getMetaInfo(file);
            System.out.println(map);
        }
    }

    public static String getMD5(InputStream input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] bytes = new byte[100000];
            int n = input.read(bytes);
            while (n != -1) {
                md.update(bytes, 0, n);
                n = input.read(bytes);
            }

            byte[] result = md.digest();
            return (new BigInteger(1, result)).toString(16);
        } catch (NoSuchAlgorithmException ignored) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取图片元信息，以Map格式返回。
     */
    public static Map<String, String> getMetaInfo(InputStream input) {
        Metadata metadata;
        HashMap<String, String> metadataMap = new HashMap<>();
        try {
            metadata = ImageMetadataReader.readMetadata(input);
        } catch (ImageProcessingException | IOException e) {
            return metadataMap;
        }

        for(Directory directory : metadata.getDirectories()) {
            if(directory == null) {
                continue;
            }
            for(Tag tag : directory.getTags()) {
                metadataMap.put(tag.getTagName(), tag.getDescription());
            }
        }
        return metadataMap;
    }
}
